#!/bin/sh

# Wrapper script for nevernoid to allow read-only shared data
# files, plus writable per-user highscore/settings in ~/nevernoid
# Author: B. Watson (yalhcru@gmail.com)

# How lame is this? The game opens the map files O_RDWR (read/write
# access), even though it never attempts to write to them! Also, it
# doesn't use fopen() to do this (I tried a LD_PRELOAD to fix it).

# Because it's closed-source, I can't fix it, and because of this silliness,
# the user directory needs to contain a *copy* of all the map files
# rather than just symlinks to them. Fortunately they're small files.

# A proper fix would involve either:
# - The original author fixing the source and recompiling, or
# - Someone well-versed in Linux-flavored 80x86 assembly to disassemble
#   the code, find the offending O_RDWR byte, and replace with the value
#   of O_RDONLY. This assumes that the call to open() is a separate call
#   than the one that opens the highscores.dat/options.dat files for
#   writing! This is complicated by the fact that the code was compiled
#   with FreePascal instead of being written in the more familiar C...

GAME=nevernoid
USERDIR=~/.$GAME
BIN=/usr/libexec/$GAME
SHARE=/usr/share/$GAME
LINKDIRS="fonts music sounds sprites"
COPYDIRS="maps"

set -e

if [ ! -e $USERDIR ]; then
	mkdir $USERDIR
	echo "$0: Created $USERDIR/"
fi

cd $USERDIR

for dir in $LINKDIRS; do
	if [ ! -e $dir ]; then
		echo "$0: linking $SHARE/$dir/ to $USERDIR/$dir/"
		ln -s $SHARE/$dir $dir
	fi
done

for dir in $COPYDIRS; do
	if [ ! -e $dir ]; then
		echo "$0: copying $SHARE/$dir/ to $USERDIR/$dir/"
		cp -r $SHARE/$dir $dir
	fi
done

exec $BIN
